from maintenance import models
from django.http import JsonResponse
from django.shortcuts import render, redirect
from maintenance.utils.form import RepairModelForm
from maintenance.utils.pagination import Pagination
from django.views.decorators.csrf import csrf_exempt


# Create your views here.

def repair_list(request):
    queryset = models.RepairPreorder.objects.filter(user_id=request.session['info']['id']).order_by('date')
    page_object = Pagination(request, queryset, page_size=2)
    form = RepairModelForm()
    context = {
        "form": form,
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, 'repair_list.html', context)


def repair_delete(request):
    uid = request.GET.get('uid')
    exists = models.RepairPreorder.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({'status': False, 'error': '删除失败，数据不存在。'})
    models.RepairPreorder.objects.filter(id=uid).delete()
    return JsonResponse({'status': True})


def repair(request):
    return render(request, 'repair.html')


def repair_add(request):
    if request.method == "GET":
        form = RepairModelForm()
        return render(request, 'repair_add.html', {"form": form})
    form = RepairModelForm(data=request.POST)
    if form.is_valid():
        form.instance.user_id = request.session['info']['id']
        form.save()
        return redirect('/repair/list/')
    return render(request, 'repair_add.html', {"form": form})


def repair_detail(request):
    """ 根据uid获取预约详细 """
    uid = request.GET.get('uid')
    row_dict = models.RepairPreorder.objects.filter(id=uid).values('name', 'email', 'phone_number', 'car_type', 'date',
                                                                   'area', 'specific').first()
    if not row_dict:
        return JsonResponse({'status': False, 'error': '数据不存在。'})

    result = {
        'status': True,
        'data': row_dict
    }
    return JsonResponse(result)


@csrf_exempt
def repair_edit(request):
    """ 编辑预约信息 """
    uid = request.GET.get('uid')
    row_object = models.RepairPreorder.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'tip': '数据不存在，请刷新重试'})

    form = RepairModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def repair_detail1(request):
    return render(request,'repair_detail1.html')


def repair_detail2(request):
    return render(request,'repair_detail2.html')